import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
import org.xml.sax.SAXException;


/**
 * @author alek
 *
 */
public class XmlInterfaceData extends DefaultInterfaceData {
	private static final long serialVersionUID = 1L;

	public boolean importXML(InputStream in) throws ParserConfigurationException, SAXException, IOException
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;

			builder = factory.newDocumentBuilder();
			
			Document doc=builder.parse(in);
			CII_Tree_Vectors tmp=new CII_Tree_Vectors();
			tmp.setSize(9);

			Element root=doc.getDocumentElement();
			
			if(root!=null)
			{
			tmp.set(1,root.getAttribute("name"));
			tmp.set(2,root.getAttribute("type"));
			tmp.set(3,root.getAttribute("cellsize"));
			tmp.set(4,root.getAttribute("rows"));
			tmp.set(5,root.getAttribute("columns"));
			tmp.set(6,root.getAttribute("access"));
			tmp.set(7,root.getAttribute("address"));
			tmp.set(8,root.getAttribute("position"));
			}
			setInterface(tmp);
			
			for(int y=0;y<mSize.height;y++)
			{
				Element row;
				row=getRowByID(root,Integer.toString(y));

				for(int x=0;x<mSize.width;x++)
				{
					if(row!=null)
					{
						Element cell=getCell(row,x);
						if(cell!=null)
						{

							String txt=cell.getTextContent();
							if(txt.length()>0) mData[x][y]=Integer.parseInt(txt);
							else mData[x][y]=null;
						} else ;
					} else ;
				}
			}

	return true;
	}
	
	public boolean exportXML(OutputStream os,List<Rectangle> areas)
	{
		try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();

		Document expdoc=builder.newDocument();
		
		if(areas==null)
		{
			areas=new Vector<Rectangle>();
			areas.add(new Rectangle(0,0,this.mSize.width,mSize.height));
		}
		
		Vector<Object> data= getData(areas);

		Element root=expdoc.createElement("interface");
		root.setAttribute("name",mInterface.get(1)); 
		root.setAttribute("type",mInterface.get(2));
		root.setAttribute("cellsize",mInterface.get(3));
		root.setAttribute("rows",mInterface.get(4));
		root.setAttribute("columns",mInterface.get(5));
		root.setAttribute("access",mInterface.get(6));
		root.setAttribute("address",mInterface.get(7));
		root.setAttribute("position",mInterface.get(8));
		expdoc.appendChild(root);
		
		Iterator<Rectangle> it=areas.iterator();
		Iterator<Object> dit=data.iterator();
		while(it.hasNext())
		{
			Rectangle rct=it.next();
			System.out.println(rct.toString());
			for(int y=rct.y;y<rct.y+rct.height;y++)
			{
				Element row;
				row=getRowByID(root,Integer.toString(y));
				if(row==null)
				{
					row=expdoc.createElement("row");
					row.setAttribute("y", Integer.toString(y));
					row.setIdAttribute("y", true);
					root.appendChild(row);
				}
				for(int x=rct.x;x<rct.x+rct.width;x++)
				{
					Object obj=dit.next();
					if(obj==null) continue;
					Element cell;
					cell=getCell(row,x);
					if(cell==null)
					{
							cell=expdoc.createElement("cell");
							cell.setAttribute("x", Integer.toString(x));
							row.appendChild(cell);
					}
					
					cell.setTextContent(obj.toString()); 
				}
				if(!row.hasChildNodes()) root.removeChild(row);
			}
		}

		
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer;
        
		transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(expdoc);
        StreamResult result =  new StreamResult(os);
        //transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"interface.dtd");
               
        transformer.transform(source, result);

		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private Element getRowByID(Element root,String id)
	{
		NodeList nl=root.getChildNodes();
		for(int i=0;i<nl.getLength();i++)
		{
			Element el=(Element) nl.item(i);
			if(el.getAttribute("y").equals(id)) return el;
		}
		return null;
	}
	private Element getCell(Element row,int x)
	{
		NodeList nl=row.getChildNodes();
		for(int i=0;i<nl.getLength();i++)
		{
			Element el=(Element) nl.item(i);
			if(Integer.parseInt(el.getAttribute("x"))==x) return el;
		}
		return null;
	}
}
